(function($) {
   $.widget('ui.imageGallery', {
         options:
         {
            list:[],
            origin: false,
            template: "template.html",
            template_name: "image_gallery"
         },
         //шаблон

         _create: function() {
           var this_ = this;
           if (!this.options.list.length) {
               this.element.find('>*').each(function() {
                    var el = $(this);
                    this_.options.list.push(el.attr('src') || el.attr('rel') || el.text());
               });
               if (!this.options.list.length) return;
           }
           
           this._render();
        },

        //отрисовка
        _render: function() {
            var this_ = this;
            //загружаем шаблон
            app.main.getTemplate(this.options.template, function(){
                this_._buildTable();
            });
        },

        //перерисовываем данные
        _buildTable: function() {
           var this_ = this;
           this.element.html('')
            .append($.tmpl(this.options.template_name, this.options))
            .find('.list .img_list').imageItem()
                .click(function(){
                    this_.changeTo($(this).attr('rel'));
                });
           
           this.options.origin = {
                width: this.element.width(),
                height: this.element.height()-this.element.find('.list').height()-12
            }
            this.element.find('.current').css({
               height: this.options.origin.height
           });
           this.changeTo(this.options.list[0]);
         },

         changeTo: function(url) {
             var this_ = this;
             var div = $('<div>').attr('rel', url).css(
             {
                width: this.options.origin.width,
                height: this.options.origin.height
             })
                .imageItem({
                    size: this.options.origin
                })
                .click(function(){
                    var index = $.inArray($(this).attr('rel'), this_.options.list);
                    if (index == -1) return;
                    var next = index + 1;
                    if (next == this_.options.list.length){
                        next = 0;
                    }
                    this_.changeTo(this_.options.list[next]);
                });
             this.element.find('.current').html('').append(div);
         }
   })
})(jQuery);

